<template>
	<view class="container">
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-wrapper">
			<image src="/static/loading.gif" class="loading-icon" />
			<text>加载中...</text>
		</view>

		<!-- 顶部导航栏 -->
		<view class="nav-bar glassmorphism">
			<view class="flex items-center">
				<checkbox class="checkbox-style mr-2" :checked="isAllChecked == 1" @click="toggleAllCheck" />
				<text class="select-all">全选</text>
			</view>
			<text class="delete-btn" @click="confirmDelete">
				<image src="/static/delete-icon.svg" class="icon" />
			</text>
		</view>

		<!-- 商品列表 -->
		<scroll-view class="product-list" scroll-y refresher-enabled :refresher-triggered="isRefreshing"
			@refresherrefresh="onRefresh">
			<view class="product-card" v-for="(product, index) in products" :key="product.goodsId"
				@touchstart="startTouch(index, $event)" @touchend="endTouch($event)">
				<checkbox class="checkbox-style" :checked="product.checked == 1" @click="toggleProductCheck(product)" />
				<image :src="product.image" class="product-image" mode="aspectFill" />
				<view class="product-details">
					<text class="product-title">{{product.name}}</text>
					<view class="price-section">
						<text class="current-price">¥{{formatPrice(product.price)}}</text>
						<text v-if="product.originalPrice" class="original-price">
							¥{{formatPrice(product.originalPrice)}}
						</text>
					</view>
					<view class="quantity-control">
						<view class="control-btn minus" @click="minusQuantity(product)"
							:class="{ disabled: product.quantity <= 1 }">-</view>
						<input type="number" class="quantity-input" :value="product.quantity"
							@blur="updateQuantity(product, $event)" />
						<view class="control-btn plus" @click="plusQuantity(product)">+</view>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-if="!loading && products.length === 0" class="empty-state">
				<image src="/static/empty-cart.png" class="empty-image" />
				<text class="empty-text">购物车空空如也</text>
				<button class="browse-btn" @click="goToHome">去逛逛</button>
			</view>
		</scroll-view>

		<!-- 底部结算栏 -->
		<view v-if="products.length > 0" class="checkout-bar">
			<view class="price-summary">
				<view class="total-line">
					<text class="total-label">商品合计：</text>
					<text class="total-price">¥{{formatPrice(totalPrice)}}</text>
				</view>
				<view class="delivery-line">
					<text class="delivery-fee">(含运费 ¥{{formatPrice(deliveryFee)}})</text>
				</view>
			</view>
			<button class="checkout-btn gradient-bg" :class="{ disabled: checkedCount === 0 }" @click="handleCheckout">
				结算 ({{checkedCount}})
			</button>
		</view>

		<!-- 删除确认弹窗 -->
		<uni-popup ref="deletePopup" type="dialog">
			<uni-popup-dialog type="warning" title="确认删除" content="确定要删除选中的商品吗？" @confirm="deleteCheckedProducts"
				@cancel="cancelDelete" />
		</uni-popup>
	</view>
</template>

<script>
	import {
		request
	} from '@/utils/request';

	export default {
		data() {
			return {
				products: [],
				totalPrice: 0,
				deliveryFee: 5.00,
				showDeleteModal: false, // 删除确认弹窗
				loading: true,
				isRefreshing: false,
				touchStartX: 0,
				currentIndex: -1
			};
		},
		computed: {
			checkedProducts() {
				return this.products.filter(p => p.checked)
			},
			checkedCount() {
				return this.checkedProducts.length
			},
			isAllChecked: {
				get() {
					return this.products.length > 0 &&
						this.products.every(p => p.checked)
				},
				set(val) {
					this.products.forEach(p => {
						this.$set(p, 'checked', val ? 1 : 0)
					})
				}
			}
		},
		watch: {
			products: {
				deep: true,
				immediate: true,
				handler() {
					this.calculateTotalPrice()
				}
			}
		},
		methods: {
			confirmDelete() { // 确认删除
				if (this.hasCheckedItems) {
					this.showDeleteModal = true;
				} else {
					uni.showToast({
						title: '请选择要删除的商品',
						icon: 'none'
					});
				}
			},
			cancelDelete() {
				this.showDeleteModal = false;
			},
			async deleteCheckedProducts() {
				const checkedIds = this.products
					.filter(p => p.checked)
					.map(p => p.id);

				try {
					const res = await request({
						url: 'shoppingCart/deleteBatchShoppingCart',
						method: 'POST',
						data: {
							ids: checkedIds
						}
					});

					if (res.code === 200) {
						await this.queryShoppingCarts();
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
					}
				} catch (error) {
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					});
				}
			},
			// 勾选单个商品
			toggleProductCheck(product) {
				this.$set(product, 'checked', product.checked ? 0 : 1)
			},
			minusQuantity(product) { // 减少商品数量
				if (product.quantity > 1) {
					product.quantity--;
					this.calculateTotalPrice();
				}
			},
			plusQuantity(product) { // 增加商品数量
				product.quantity++;
				this.calculateTotalPrice();
			},
			toggleAllCheck() { // 切换全选状态
				this.isAllChecked = this.isAllChecked == 1 ? 0 : 1;
				this.products.forEach(product => {
					product.checked = this.isAllChecked;
				});
				this.calculateTotalPrice();
			},
			// 计算总价
			calculateTotalPrice() {
				this.totalPrice = this.checkedProducts.reduce(
					(sum, p) => sum + (p.price * p.quantity), 0
				)
			},
			// 结算逻辑
			async handleCheckout() {
				if (this.checkedCount === 0) {
					uni.showToast({
						title: '请选择商品',
						icon: 'none'
					})
					return
				}

				try {
					const res = await request({
						url: 'order/addOrder',
						method: 'POST',
						data: this.checkedProducts.map(p => ({
							goodsId: p.goodsId,
							quantity: p.quantity,
							checked: p.checked ? 1 : 0
						}))
					})

					if (res.code === 200) {
						uni.navigateTo({
							url: `/pages/shoppingcart/confirmOrder?totalPrice=` + (this.totalPrice + this.deliveryFee) +
							`&products=` + JSON.stringify(this.checkedProducts)
						})
					}
				} catch (error) {
					console.error('结算失败:', error)
				}
			},
			formatPrice(price) { // 格式化价格
				return price.toFixed(2);
			},
			async queryShoppingCarts() {
				try {
					this.loading = true;
					const res = await request({
						url: 'shoppingCart/queryShoppingCart',
						method: 'GET'
					});

					if (res.code === 200) {
						this.products = res.data.map(item => ({
							...item,
							checked: Number(item.checked) || 0
						}));
						this.calculateTotalPrice();
					}
				} catch (error) {
					uni.showToast({
						title: '数据加载失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
					this.isRefreshing = false;
				}
			},
			// 新增下拉刷新
			onRefresh() {
				this.isRefreshing = true;
				this.queryShoppingCarts();
			},

			// 修正后的触摸处理方法
			startTouch(index, e) {
				if (!e?.touches) return
				this.touchStartX = e.touches[0].clientX
				this.currentIndex = index
			},

			endTouch(e) {
				if (!e?.changedTouches) return
				const touchEndX = e.changedTouches[0].clientX
				if (touchEndX - this.touchStartX < -60) {
					this.showDeletePopup(this.currentIndex)
				}
			},

			// 新增删除弹窗控制方法
			showDeletePopup(index) {
				this.currentIndex = index
				this.$refs.deletePopup.open()
			},

			goToHome() {
				uni.switchTab({
					url: '/pages/index/index'
				});
			}
		},
		onShow() {
			this.queryShoppingCarts();
		}
	};
</script>

<style scoped lang="scss">
	/* 现代设计风格 */
	$primary: #06c48a;
	$secondary: #ff4757;
	$background: #f8f9fa;
	$text-primary: #2d3436;
	$text-secondary: #636e72;

	.container {
		background: $background;
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.loading-wrapper {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		text-align: center;

		.loading-icon {
			width: 80rpx;
			height: 80rpx;
			margin-bottom: 20rpx;
		}
	}

	.nav-bar.glassmorphism {
		background: rgba(255, 255, 255, 0.9);
		backdrop-filter: blur(10px);
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
		padding: 24rpx 32rpx;

		.select-all {
			font-size: 32rpx;
			color: $text-primary;
		}

		.delete-btn .icon {
			width: 48rpx;
			height: 48rpx;
		}
	}

	.product-card {
		background: white;
		border-radius: 24rpx;
		margin: 20rpx 32rpx;
		padding: 32rpx;
		display: flex;
		align-items: center;
		transition: transform 0.2s;

		&:active {
			transform: scale(0.98);
		}

		.product-image {
			width: 160rpx;
			height: 160rpx;
			border-radius: 16rpx;
			margin: 0 32rpx;
		}

		.product-details {
			flex: 1;

			.product-title {
				font-size: 34rpx;
				color: $text-primary;
			}

			.current-price {
				color: $secondary;
				font-size: 36rpx;
				font-weight: 600;
			}

			.original-price {
				color: $text-secondary;
				text-decoration: line-through;
				margin-left: 16rpx;
			}
		}
	}

	.quantity-control {
		display: flex;
		align-items: center;
		margin-top: 24rpx;

		.control-btn {
			width: 64rpx;
			height: 64rpx;
			border-radius: 50%;
			background: $background;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 40rpx;

			&.disabled {
				opacity: 0.5;
			}
		}

		.quantity-input {
			width: 96rpx;
			margin: 0 16rpx;
			text-align: center;
			font-weight: 500;
		}
	}

	.checkout-bar {
		padding: 24rpx 32rpx;

		.price-summary {
			flex: 1;
			margin-right: 32rpx;

			.total-line {
				display: flex;
				align-items: baseline;
				margin-bottom: 8rpx;

				.total-label {
					font-size: 28rpx;
					color: $text-secondary;
				}

				.total-price {
					color: $secondary;
					font-size: 36rpx;
					font-weight: 600;
					margin-left: 12rpx;
				}
			}

			.delivery-line {
				.delivery-fee {
					font-size: 24rpx;
					color: $text-secondary;
				}
			}
		}

		.checkout-btn {
			min-width: 240rpx;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 32rpx;
		}
	}

	.empty-state {
		text-align: center;
		padding: 100rpx 0;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.empty-image {
			width: 300rpx;
			height: 300rpx;
			opacity: 0.8;
		}

		.empty-text {
			color: $text-secondary;
			margin: 32rpx 0;
		}

		.browse-btn {
			width: 240rpx;
			background: $primary;
			color: white;
			border-radius: 48rpx;
		}
	}
</style>